import Vue from 'vue'
import Vuex from 'vuex'
//引入微擎配置
import util from '../static/js/util.js'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		openid: '',
		config: {},
	},
	mutations: {
		setOpenid(state, openid) {
			state.openid = openid
		},
		setConfig(state, config) {
			state.config = config
		},
	},
    getters:{
        currentColor(state){
            return state.colorList[state.colorIndex]
        }
    },
	actions: {
		// lazy loading openid
		getUserOpenId: async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid)
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							setTimeout(function () { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								console.log('uni.request mock openid[' + openid + ']');
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
		},
		/**
		 * 全局配置
		 */
		setConfigAsync: async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				const config = uni.getStorageSync('config');
				if(config){
					commit('setConfig', config)
					resolve(config)
				}else{
					//获取全局配置
					let url = '';
						//#ifdef MP-WEIXIN
						url = 'entry/wxapp/config'
						//#endif
						//#ifdef H5
						url = 'entry/site/config'
						//#endif
					util.request({
						// 小程序端执行
						url : url,
						data: {
							action : '',
							m: 'muu_classroom'
						},
						success: function (res) {
							if (res.data.code == 200) {
								uni.setStorageSync('config', res.data.data)
								commit('setConfig', res.data.data)
							}
							resolve(res.data.data)
						}
					})
				}
			})
		}

	}
})

export default store
